//
//  WriteViewController.m
//  Moko
//
//  Created by cj848 on 11. 7. 23..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WriteViewController.h"
#import "MokoAppDelegate.h"
#import "SeekoArticleTableViewController.h"
#import "SeekoBoardListTableViewController.h"
#import "UIImageCategory.h"
#import "ParsingDirector.h"
#import <QuartzCore/QuartzCore.h>
@implementation WriteViewController
@synthesize isModify;
@synthesize writeAndModVO;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil isModify:(BOOL)bModify vo:(NSDictionary*)writeVO {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        isModify = bModify;
        if( isModify )
            assert([writeVO objectForKey:@"id"] != nil && [writeVO objectForKey:@"title"] != nil && [writeVO objectForKey:@"content"] != nil && [writeVO objectForKey:@"no"] != nil);
        writeAndModVO = [writeVO copy];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShown:)
                                                     name:UIKeyboardDidShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    ((UIScrollView*)self.view).contentInset = contentInsets;
    ((UIScrollView*)self.view).scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    [((UIScrollView*)self.view) setContentSize:CGSizeMake(aRect.size.width, aRect.size.height + kbSize.height + 50)];
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
        CGRect aRect = self.view.frame;
        aRect.size.height -= kbSize.height;
        [((UIScrollView*)self.view) setContentSize:CGSizeMake(aRect.size.width, aRect.size.height + kbSize.height + 50)];
        if (activeView != nil && !CGRectContainsRect(aRect, activeView.frame) ) {
            CGPoint scrollPoint = CGPointMake(0.0, activeView.frame.origin.y+activeView.frame.size.height-kbSize.height);
            [((UIScrollView*)self.view) setContentOffset:scrollPoint animated:YES];
        }
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    ((UIScrollView*)self.view).contentInset = contentInsets;
    ((UIScrollView*)self.view).scrollIndicatorInsets = contentInsets;
    [((UIScrollView*)self.view) setContentSize:writeView.frame.size];
}
-(void)backStep {
    [thread cancel];
    [thread release];
    thread = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)hideKeyboard:(id)sender {
    NSArray* subviews = [writeView subviews];
    for( UIView* views in subviews ) 
        [views resignFirstResponder];
}


-(IBAction) registration {
    GET_APPDELEGATE;
    
    if( [titleField.text length] == 0 ) {
        UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"등록불가." message:@"제목은 필수 입력사항입니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [av show];
        [av release];
        return;
    }
    else if ([contentTextView.text length] == 0 ) {
        UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"등록불가." message:@"내용은 필수 입력사항입니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [av show];
        [av release];
        return;
    }
    int charset = delegate.httpClient.charset;
    
    NSString* boundary = @"---zzzdfss--osifaryForHHH";
    // 데이터 넣기
    
    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"subject\"\r\n\r\n"] dataUsingEncoding:charset]];
    [body appendData:[titleField.text dataUsingEncoding:charset]];
    
    if( attachImage1 != nil ) {
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
        [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file1\"; filename=\"file1.jpg\"\r\n\r\n"] dataUsingEncoding:charset]];
        // 시코에서만 문제가 있는듯
        //[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:charset]];
        NSData* imageData = UIImageJPEGRepresentation(attachImage1, 0.9f);
        [body appendData:[NSData dataWithData:imageData]];
        
    }
    if( attachImage2 != nil ) {
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
        [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file2\"; filename=\"file2.jpg\"\r\n\r\n"] dataUsingEncoding:charset]];
        // 시코에서만 문제가 있는듯 원래는 파일 타입 넣어줘야됨
        //[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:charset]];
        NSData* imageData = UIImageJPEGRepresentation(attachImage2, 0.9f);
        [body appendData:[NSData dataWithData:imageData]];
    }

    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"id\"\r\n\r\n"] dataUsingEncoding:charset]];
    [body appendData:[[writeAndModVO objectForKey:@"id"] dataUsingEncoding:charset]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"check\"\r\n\r\n"] dataUsingEncoding:charset]];
    [body appendData:[@"1" dataUsingEncoding:charset]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"use_html\"\r\n\r\n"] dataUsingEncoding:charset]];
    [body appendData:[@"1" dataUsingEncoding:charset]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"sitelink1\"\r\n\r\n"] dataUsingEncoding:charset]];
    [body appendData:[sitelinkTextField.text dataUsingEncoding:charset]];
       
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"memo\"\r\n\r\n"] dataUsingEncoding:charset]];
    // 낙인은 아래와 같은 메시지
    NSString* nakin = delegate.configVO.writeSignature;
    // 글쓰기 일때, 낙인 사용 옵션 체크시에만 낙인 들어감
    if( isModify == NO && [delegate.configVO.useWriteSignature boolValue] == YES && [contentTextView.text rangeOfString:nakin].location != NSNotFound )
        contentTextView.text = [NSString stringWithFormat:@"%@\n\n%@", contentTextView.text, nakin];
    [body appendData:[[contentTextView.text stringByReplacingOccurrencesOfString:@"\n" withString:@"\r\n"]dataUsingEncoding:charset]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"mode\"\r\n\r\n"] dataUsingEncoding:charset]];
    
    if( isModify == NO ) {
        [body appendData:[@"write" dataUsingEncoding:charset]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:charset]];
    }
    else {
        [body appendData:[@"modify" dataUsingEncoding:charset]];
        
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:charset]];
        [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"no\"\r\n\r\n"] dataUsingEncoding:charset]];
        [body appendData:[[writeAndModVO objectForKey:@"no"] dataUsingEncoding:charset]];
        
        // 마지막 바운더리
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:charset]];
    }
    
    // 데이터 넣기 종료
    [delegate.httpClient requestURL:action httpMethod:@"POST" bodyData:body isMultiPart:YES boundary:boundary target:self selector:@selector(finishLoading:)];
}
//파일 첨부 메소드
- (IBAction)attachImage:(id)sender {
    UIActionSheet* sheet = [[UIActionSheet alloc] init];
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
        sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    }
    //sheet.cancelButtonIndex = 0;
    sheet.delegate = self;
    [sheet addButtonWithTitle:@"취소"];
    [sheet addButtonWithTitle:@"앨범에서 가져오기"];
    // 카메라가 있으면 버튼 추가
    if( [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] )
        [sheet addButtonWithTitle:@"카메라로 직접 찍기"];
    
    currentAttachTag = ((UIButton*)sender).tag;
    // 첨부 1일때
    // 수정일때는 del_file이란 멤버에 값이 있음...
    if( currentAttachTag == 1 ) {
        if( attachImage1 != nil ) {
            [sheet addButtonWithTitle:@"첨부 삭제"];
        }
    } else {
        if( attachImage2 != nil ) {
            [sheet addButtonWithTitle:@"첨부 삭제"];
        }
    }
    [sheet showFromTabBar:self.tabBarController.tabBar];
    [sheet release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 앨범에서 가져오기
    if( buttonIndex == 0 ) {
        if( attachImage1 != nil )
            imageAttach1Button.titleLabel.text = @"첨부됨";
        if( attachImage2 != nil )
            imageAttach2Button.titleLabel.text = @"첨부됨";
    }
    if( buttonIndex == 1 ) {
        if( [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary] ) {
            UIImagePickerController* picker = [[[UIImagePickerController alloc] init] autorelease];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
                [self presentModalViewController:picker animated:YES];
            }
            else {
                popOverController = [[UIPopoverController alloc] initWithContentViewController:picker];
                [popOverController setPopoverContentSize:CGSizeMake(320, 640) animated:YES];
                CGRect frame = CGRectZero;
                if( currentAttachTag == 1 ) {
                    frame = [self.view convertRect:imageAttach1Button.frame toView:self.view];
                } else {
                    frame = [self.view convertRect:imageAttach2Button.frame toView:self.view];
                }
                [popOverController presentPopoverFromRect:frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES]; 
            }
        }
    } 
    // 카메라로 직접 찍기 or 첨부 삭제
    else if( buttonIndex == 2 ) {
        if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"카메라로 직접 찍기"] ) {
            if( [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera] ) {
                UIImagePickerController* picker = [[[UIImagePickerController alloc] init] autorelease];
                picker.delegate = self;
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
                    [self presentModalViewController:picker animated:YES];
                }
                else {
                    popOverController = [[UIPopoverController alloc] initWithContentViewController:picker];
                    [popOverController setPopoverContentSize:CGSizeMake(320, 320) animated:YES];
                    CGRect frame = CGRectZero;
                    if( currentAttachTag == 1 ) {
                        frame = [self.view convertRect:imageAttach1Button.frame toView:self.view];
                    } else {
                        frame = [self.view convertRect:imageAttach2Button.frame toView:self.view];
                    }
                    [popOverController presentPopoverFromRect:frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES]; 
                }
            }
        }// 첨부 삭제
        else {
            if( currentAttachTag == 1 ) {
                [attachImage1 release];
                attachImage1 = nil;
                imageAttach1Button.titleLabel.text =@"첨부 이미지 1";
            }
            else {
                [attachImage2 release];
                attachImage2 = nil;
                imageAttach2Button.titleLabel.text = @"첨부 이미지 2";
            }
        }
    } // 이것도 무조건 첨부삭제
    else if( buttonIndex == 3 ) {
        if( currentAttachTag == 1 ) {
            [attachImage1 release];
            attachImage1 = nil;
            imageAttach1Button.titleLabel.text =@"첨부 이미지 1";
        }
        else {
            [attachImage2 release];
            attachImage2 = nil;
            imageAttach2Button.titleLabel.text = @"첨부 이미지 2";
        }
    }
}
-(void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    NSLog(@"release popover");
    [popOverController release];
}
// 사진 앨범에서 선택
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if( image.size.height > 500 )
        image = [image ResizedLimitedWidth:0 height:500];
    if( currentAttachTag == 1 ) {
        attachImage1 = [image retain];
        imageAttach1Button.titleLabel.text = @"첨부됨";
    }
    else {
        attachImage2 = [image retain];
        imageAttach2Button.titleLabel.text = @"첨부됨";
    }
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
        [picker dismissModalViewControllerAnimated:YES];
    } else {
        [picker dismissModalViewControllerAnimated:YES];
        [popOverController dismissPopoverAnimated:YES];
    }
}
-(void)modify:(BOOL)mod {
    [self.navigationItem.rightBarButtonItem setTitle:(mod) ? @"수정":@"글쓰기"];
    isModify = mod;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self hideKeyboard:touches];
}

- (void)dealloc
{
    [thread release];
    [attachImage1 release];
    [attachImage2 release];
    [writeAndModVO release];
    [titleField release];
    [contentTextView release];
    [sitelinkTextField release];
    [imageAttach1Button release];
    [imageAttach2Button release];
    [writeView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    GET_APPDELEGATE;
    action = [[NSString stringWithFormat:@"%@/zboard4/write_ok.php", delegate.configVO.siteHostAddress] retain];
    //[self.view setBackgroundColor:RGB(204,204,204)];
    UIBarButtonItem* ritem = [[UIBarButtonItem alloc] initWithTitle:@"글쓰기" style:UIBarButtonItemStylePlain target:self action:@selector(registration)];
    [self.navigationItem setRightBarButtonItem:ritem];
    [ritem release];

    if( isModify ) {
        titleField.text = [writeAndModVO objectForKey:@"title"];
        contentTextView.text = [writeAndModVO objectForKey:@"content"];
    }
    // 백버튼 커스터마이징
    // backBarButtonItem 이었나 암튼 이거로는 커스텀뷰가 안돼서 이렇게 지정
    UIImage* image = [UIImage imageNamed:@"back_left_button.png"];
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backStep) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, image.size.width/2, image.size.height/2);
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = item;
    [item release];
    self.title = [writeAndModVO objectForKey:@"title"];
    sitelinkTextField.text = [writeAndModVO objectForKey:@"link"];
    
    // 우측 버튼 세팅
    if( isModify == NO ) 
        image = [UIImage imageNamed:@"write_right_button.png"];
    else
        image = [UIImage imageNamed:@"modify_right_button.png"];
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    if( [self.navigationController.navigationBar bounds].size.height > image.size.height )
        button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    else
        button.frame = CGRectMake(0, 0, 25, 25);
    [button addTarget:self action:@selector(registration) forControlEvents:UIControlEventTouchUpInside];
    item = [[UIBarButtonItem alloc] initWithCustomView:button];
    [self.navigationItem setRightBarButtonItem:item];
    [item release];
    contentTextView.placeholder = @"내용을 입력하세요\n제목, 링크, 내용은 5초에 한번씩 자동 저장됩니다.";
    contentTextView.delegate = self;
    contentTextView.layer.cornerRadius = 7;
    contentTextView.clipsToBounds = YES;
    firstContentTextViewFrame = contentTextView.frame;

    if( [delegate.backupWriteTexts.title length] > 0 || [delegate.backupWriteTexts.content length] > 0 ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"저장된 데이터가 있습니다." message:@"복원 하시겠습니까?\n복원하지 않는 경우 저장된 데이터는 사라집니다." delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
        alert.tag = 111;
        [alert show];
        [alert release];
    } else {
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(tempSaveThread) object:nil];
        [thread start];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 111 ) {
        GET_APPDELEGATE;
        if( buttonIndex == 1 ) {
            titleField.text = delegate.backupWriteTexts.title;
            contentTextView.text = delegate.backupWriteTexts.content;
            sitelinkTextField.text = delegate.backupWriteTexts.link;
            [contentTextView textChanged:nil];
        }
        else if( buttonIndex == 0 ) {
            delegate.backupWriteTexts.title = @"";
            delegate.backupWriteTexts.content = @"";
            delegate.backupWriteTexts.link = @"";
            [[delegate managedObjectContext] save:nil];
        }
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(tempSaveThread) object:nil];
        [thread start];
    }
}

-(void)tempSaveThread {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    GET_APPDELEGATE;
    while( [[NSThread currentThread] isCancelled] == NO ) {
        [self performSelectorOnMainThread:@selector(saveBackUpContents) withObject:nil waitUntilDone:YES];
        [[delegate managedObjectContext] save:nil];
        NSLog(@"저장됨");
        [NSThread sleepForTimeInterval:5];
    }
    NSLog(@"스레드 취소");
    [pool release];
}
-(void)saveBackUpContents {
    GET_APPDELEGATE;
    delegate.backupWriteTexts.title = titleField.text;
    delegate.backupWriteTexts.link = sitelinkTextField.text;
    delegate.backupWriteTexts.content = contentTextView.text;
    [contentTextView textChanged:nil];
}

-(void)textViewDidBeginEditing:(UITextView *)textView {
    activeView = textView;
}
-(void)textViewDidEndEditing:(UITextView *)textView {
    activeView = nil;
}

//-(void)textViewDidChange:(UITextView *)textView {
//    float addY = textView.frame.size.height - textView.contentSize.height;
//
//    float textview_pos = textView.frame.origin.y + textView.frame.size.height;
//    if( firstContentTextViewFrame.size.height < textView.contentSize.height ) {
//        float maxHeight = 0;
//        CGRect frame = textView.frame;
//        frame.size = textView.contentSize;
//        textView.frame = frame;
//        for( UIView* subview in [writeView subviews] ) {
//            if( [subview isEqual:textView] == NO ) {
//                if( subview.frame.origin.y > textview_pos ) {
//                    CGRect frame = subview.frame;
//                    frame.origin.y += -addY;
//                    subview.frame = frame;
//                    maxHeight = MAX(maxHeight, subview.frame.origin.y + subview.frame.size.height);
//                }
//            }
//        }
//        if( maxHeight > 0 ) {
//            CGRect frame = writeView.frame;
//            frame.size.height = maxHeight + 20;
//            writeView.frame = frame;
//            [(UIScrollView*)self.view setContentSize:frame.size];
//        }
//    }
//}
- (void)viewDidUnload
{
    [contentTextView release];
    contentTextView = nil;
    [titleField release];
    titleField = nil;
    [sitelinkTextField release];
    sitelinkTextField = nil;
    [imageAttach1Button release];
    imageAttach1Button = nil;
    [imageAttach2Button release];
    imageAttach2Button = nil;
    [writeView release];
    writeView = nil;
    thread = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [self.view becomeFirstResponder];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark UITextFieldDelegate implementation
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark 글 올리기 관련

// 기본적으로 오버라이드 돼야 할 메소드
- (void)finishLoading:(NSData*) data {
    // 기본적으로 커넥션과 데이터를 릴리즈 해야된다.
    GET_APPDELEGATE;
    ParsingDirector* director = [ParsingDirector sharedParsingDirector];
    director.responseData = data;
    NSString* error = [director getError];
    
    if( [error length] > 0 ) {
        UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"등록불가." message:error delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [av show];
        [av release];
    }
    else {
        UIAlertView* av = [[UIAlertView alloc] initWithTitle:@"등록 되었습니다." message:@"등록이 정상적으로 완료 되었습니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [av show];
        [av release];
        // 스레드 종료 후 글 제거
        [thread cancel];
        [thread release];
        thread = nil;
        delegate.backupWriteTexts.title = @"";
        delegate.backupWriteTexts.content = @"";
        delegate.backupWriteTexts.link = @"";
        [[delegate managedObjectContext] save:nil];
        NSArray* viewControllers = self.navigationController.viewControllers;
        for( UIViewController* controller in viewControllers ) {
            if( [controller isKindOfClass:[SeekoBoardListTableViewController class]] == YES ) {
                [(SeekoBoardListTableViewController*)controller loadFirstPage];
                break;
            }
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
 